package com.fanco.learn_datastruct_leetcode.juc;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * @author qiaowang 2021/8/11
 */
class MyData {
    public volatile int number;
    public AtomicInteger atomicInteger = new AtomicInteger(0);
    public void addNumber() {
        number++;
    }
    public void atomicAdd() {
        atomicInteger.getAndIncrement();
    }
}
/**
 * @author Fanco
 * @Desc 验证volatile 可见性Demo
 * MyData是资源类， 在没有添加 volatile 关键字 AAA对 number变量的修改 main线程是不知道的，所以while块一直满足
 */
public class VolatileVisibilityDemo {
    public static void main(String[] args) {
        System.out.println("可见性测试");
        MyData myData = new MyData();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 线程启动");
            myData.addNumber();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "修改后的值为" + myData.number);
        }, "AAA").start();
        while (myData.number == 0) {
        }
        System.out.println(Thread.currentThread().getName() + " 线程获取的到number值为" + myData.number);
    }
}
